package com.weixin.project.Controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weixin.project.Common.Enum.MsgStatus;
import com.weixin.project.Common.Exception.CurrentUserNullException;
import com.weixin.project.Config.Filter.CurrentUserFilter;
import com.weixin.project.Entity.Message;
import com.weixin.project.Entity.User;
import com.weixin.project.Service.MsgService;
import com.weixin.project.Service.UserService;
import com.weixin.project.Util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
public class MsgController {
    @Autowired
    UserService userService;
    @Autowired
    MsgService msgService;
    @GetMapping("/message/get_my_message")
    JSONObject getMyMsg(HttpServletRequest request, @RequestParam("page") Integer page){
        User user = userService.findCurrentUser(request);
        page --;
        Page<Message> messagePage = msgService.findMessagesOfUser(user.getId(), page);
        JSONObject ret = new JSONObject();
        ret.put("all_pages", messagePage.getTotalPages());
        ret.put("all_count", msgService.countMessagesOfUser(user.getId()));
        ret.put("not_read_count", msgService.countNotReadMessagesOfUser(user.getId()));
        JSONArray array = new JSONArray();
        List<Message> messages = messagePage.getContent();
        for (Message message:messages){
            JSONObject obj = new JSONObject();
            obj.put("content", message.getContent());
            obj.put("id", message.getId());
            obj.put("has_read", MsgStatus.hasRead(message.getStatus()));
            array.add(obj);
        }
        ret.put("messages", array);
        return ResponseUtil.success(ret);
    }

    @PostMapping("/message/read_message")
    JSONObject readMsg(HttpServletRequest request, @RequestBody JSONObject params){
        Integer msgId = params.getInteger("id");
        msgService.readMessage(msgId);
        return ResponseUtil.success();

    }
}
